#!/usr/bin/env python3
"""
智慧农业系统状态检查工具
"""

import requests
import subprocess
import time
import webbrowser
import os

def check_system_status():
    """检查系统状态"""
    print("🔍 智慧农业系统状态检查")
    print("=" * 50)
    
    # 检查进程
    print("📋 检查系统进程...")
    try:
        result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        if '智慧农业Web演示系统.py' in result.stdout:
            print("✅ 智慧农业Web系统进程：运行中")
        else:
            print("❌ 智慧农业Web系统进程：未运行")
            return False
    except Exception as e:
        print(f"❌ 进程检查失败: {e}")
        return False
    
    # 检查端口
    print("\n🌐 检查Web服务...")
    ports_to_check = [8085, 8080, 8081, 8082, 8083, 8084]
    working_ports = []
    
    for port in ports_to_check:
        try:
            response = requests.get(f'http://localhost:{port}', timeout=2)
            if response.status_code == 200:
                working_ports.append(port)
                print(f"✅ 端口 {port}：可访问")
            else:
                print(f"⚠️ 端口 {port}：响应码 {response.status_code}")
        except requests.exceptions.RequestException:
            print(f"❌ 端口 {port}：无法连接")
        except Exception as e:
            print(f"❌ 端口 {port}：检查失败 ({e})")
    
    if working_ports:
        print(f"\n🎉 发现可用服务端口: {working_ports}")
        
        # 测试API接口
        main_port = working_ports[0]
        print(f"\n🧪 测试API接口 (端口 {main_port})...")
        
        try:
            # 测试当前数据接口
            response = requests.get(f'http://localhost:{main_port}/api/current-data', timeout=5)
            if response.status_code == 200:
                data = response.json()
                print("✅ 当前数据接口：正常")
                print(f"   📊 传感器数据: {len(data)} 项")
                print(f"   🌡️ 温度: {data.get('air_temperature', 'N/A'):.1f}°C")
                print(f"   💧 湿度: {data.get('soil_moisture', 'N/A'):.1f}%")
            else:
                print(f"⚠️ 当前数据接口：响应码 {response.status_code}")
        except Exception as e:
            print(f"❌ API测试失败: {e}")
        
        # 询问是否打开浏览器
        print(f"\n🌐 系统运行正常！")
        print(f"🔗 访问地址: http://localhost:{main_port}")
        
        try:
            choice = input("\n是否在浏览器中打开系统？(y/n): ").lower().strip()
            if choice in ['y', 'yes', '是', '']:
                print("🚀 正在打开浏览器...")
                webbrowser.open(f'http://localhost:{main_port}')
                print("✅ 浏览器已打开，请查看智慧农业系统界面")
        except (EOFError, KeyboardInterrupt):
            print("\n👋 检查完成")
        
        return True
    else:
        print("\n❌ 没有发现可用的Web服务")
        return False

def restart_system():
    """重启系统"""
    print("\n🔄 正在重启智慧农业系统...")
    
    # 停止现有进程
    try:
        subprocess.run(['pkill', '-f', '智慧农业Web演示系统.py'], capture_output=True)
        print("🛑 已停止现有进程")
        time.sleep(2)
    except:
        pass
    
    # 启动新进程
    try:
        script_path = "智慧农业Web演示系统.py"
        if os.path.exists(script_path):
            print("🚀 正在启动新进程...")
            subprocess.Popen(['python3', script_path])
            print("⏳ 等待系统初始化...")
            time.sleep(5)
            
            # 重新检查状态
            if check_system_status():
                print("✅ 系统重启成功！")
            else:
                print("❌ 系统重启失败")
        else:
            print("❌ 找不到系统文件")
    except Exception as e:
        print(f"❌ 重启失败: {e}")

def main():
    """主函数"""
    try:
        if not check_system_status():
            print("\n🔧 系统未正常运行，是否尝试重启？")
            try:
                choice = input("输入 'r' 重启系统，其他键退出: ").lower().strip()
                if choice == 'r':
                    restart_system()
                else:
                    print("👋 退出状态检查")
            except (EOFError, KeyboardInterrupt):
                print("\n👋 退出状态检查")
    except KeyboardInterrupt:
        print("\n\n👋 状态检查被中断")

if __name__ == "__main__":
    main()